<template>
	<view class="container">

		<view class="pos-f w-full navbar-area bg-main">
			<view class="state-area dflex-a">
				<view v-for="(item, index) in navList" :key="index" :class="{ active: tabCurrentIndex === index }"
					class="nav-item dflex-c pos-r fs padding-lr-lg h-full" @click="tabClick(index)">
					{{ item.title }}
					<!-- <text v-if="item.cnt > 0">({{ item.cnt }})</text> -->
				</view>
			</view>
		</view>

		<swiper :current="tabCurrentIndex" :disable-touch="true" class="swiper-box swiper-area h-full" duration="300"
			@change="changeTab">
			<swiper-item class="tab-content" v-for="(tabItem, tabIndex) in navList" :key="tabIndex">
				<scroll-view class="list-scroll-content h-full" scroll-y @scrolltolower="loadData">
					<!-- 空白页 -->
					<!-- <use-empty v-if="tabItem.couponDatas.length === 0" e-style="round" e-type="cart"
						tip="暂无优惠券" btn-tip="去领券" height="93vh"></use-empty>
						 -->
					<view class="padding-lr" @click="use(item)" v-for="(item, index) in couponDatas" :key="index">
						<view class="coupon_box border-radius margin-top-sm bg-main"
							:class="[{ 'disabled': couponStatus != 0 }]">
							
							<view class="dflex-b">
								
								<view class="left pos-a h-full dflex-c dflex-flow-c">
									<view v-if="item.type == 1">
										<text class="price fs-big">{{ item.price }}</text>
									</view>
									<view v-if="item.type == 0">
										<text class="discount fs-big">{{ item.price * 10 }}</text>
									</view>
									<view class="fs-sm" v-if="item.price >= 1">直减{{ item.price }}元</view>
									<view class="fs-sm" v-else>全场通用</view>
								</view>
								
								<view class="right padding left_t flex1">
									<view class="dflex-b padding-bottom-xs">
										<view class="fwb fs">{{ item.title }}</view>
									</view>
									<view v-if="tabItem.state == 1 " class="ft-dark iconfont iconyishiyong"></view>
									<view v-if="tabItem.state == 2 " class="ft-dark iconfont iconyiguoqi"></view>
									<view class="dflex-b ft-dark fs-xs padding-bottom border-line">
										<view class="">有效期至 {{ item.end_time }}</view>
									</view>
									<!-- <view class="fs-xs ft-dark padding-top-xs">{{ item.remark || '详细信息' }}</view> -->
								</view>
								
							</view>
							
						</view>
					</view>

					<!-- 上拉加载更多 -->
				<!-- 	<use-loadmore v-if="tabItem.couponDatas.length > 0 && tabItem.loaded && tabItem.hasmore"
						:type="tabItem.loadingType"></use-loadmore> -->
						
				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
	import {
		queryUserCouponsApi,
		
		//修改用户拥有的优惠券状态
		updateUserCouponsApi,
	} from '@/api/coupon.js'
	
	import {
		mapState
	} from 'vuex';
	
	export default {
		computed: {
			...mapState(["member"])
		},
		
		data() {
			return {
				tabCurrentIndex: 0,
				navData: {},
				// navData: {
				// 	"id": 0,
				// 	"state": "已领取",
				// 	"cnt": 0,
				// 	"loadingType": "nomore",
				// 	"datas": [{
				// 		"state": "已领取",
				// 		"type": "满减",
				// 		"name": "满100减9.9",
				// 		"price": 9.9,
				// 		"member_type": "所有人",
				// 		"order_amount": 100,
				// 		"per_max": 1,
				// 		"start_time": "2021-06-10 00:00",
				// 		"end_time": "2021.12.31",
				// 		"sort": 0,
				// 		"create_time": "2021-06-10 07:45:32"
				// 	}, {
				// 		"state": "已领取",
				// 		"type": "折扣",
				// 		"name": "满100打8折",
				// 		"price": 0.8,
				// 		"member_type": "所有人",
				// 		"order_amount": 100,
				// 		"per_max": 1,
				// 		"start_time": "2021-06-10 00:00",
				// 		"end_time": "2021.12.31",
				// 		"sort": 0,
				// 		"create_time": "2021-06-10 07:46:19"
				// 	}, {
				// 		"state": "已领取",
				// 		"type": "满减",
				// 		"name": "满100减9.9",
				// 		"price": 9.9,
				// 		"member_type": "所有人",
				// 		"order_amount": 100,
				// 		"per_max": 1,
				// 		"start_time": "2021-06-10 00:00",
				// 		"end_time": "2021.12.31",
				// 		"sort": 0,
				// 		"create_time": "2021-06-10 07:45:32"
				// 	}, {
				// 		"state": "已领取",
				// 		"type": "折扣",
				// 		"name": "满100打8折",
				// 		"price": 0.8,
				// 		"member_type": "所有人",
				// 		"order_amount": 100,
				// 		"per_max": 1,
				// 		"start_time": "2021-06-10 00:00",
				// 		"end_time": "2021.12.31",
				// 		"sort": 0,
				// 		"create_time": "2021-06-10 07:46:19"
				// 	}, {
				// 		"state": "已领取",
				// 		"type": "满减",
				// 		"name": "满100减9.9",
				// 		"price": 9.9,
				// 		"member_type": "所有人",
				// 		"order_amount": 100,
				// 		"per_max": 1,
				// 		"start_time": "2021-06-10 00:00",
				// 		"end_time": "2021.12.31",
				// 		"sort": 0,
				// 		"create_time": "2021-06-10 07:45:32"
				// 	}, {
				// 		"state": "已领取",
				// 		"type": "折扣",
				// 		"name": "满100打8折",
				// 		"price": 0.8,
				// 		"member_type": "所有人",
				// 		"order_amount": 100,
				// 		"per_max": 1,
				// 		"start_time": "2021-06-10 00:00",
				// 		"end_time": "2021.12.31",
				// 		"sort": 0,
				// 		"create_time": "2021-06-10 07:46:19"
				// 	}],
				// 	"loaded": true
				// },
				
				couponDatas: [],
				// 要查询的优惠券状态
				couponStatus: 0,
				// 修改后优惠券状态
				new_status: 2,
				//当前时间戳
				new_time: '',
				// 防止重加载
				oneloading: true,
				
				navList: [
					{
						id: 0,
						title: '已领取',
						// cnt: 0,
						// loadingType: 'more',
						// datas: [{
						// 	"state": "已领取",
						// 	"type": "满减",
						// 	"name": "满100减9.9",
						// 	"price": 9.9,
						// 	"member_type": "所有人",
						// 	"order_amount": 100,
						// 	"per_max": 1,
						// 	"start_time": "2021-06-10 00:00",
						// 	"end_time": "2021.12.31",
						// 	"sort": 0,
						// 	"create_time": "2021-06-10 07:45:32"
						// }]
						// datas: [],
						// couponDatas: [],
					},
					
					{
						id: 1,
						title: '已使用',
						// cnt: 0,
						// loadingType: 'more',
						// datas: [],
						// couponDatas: [],
					},
					{
						id: 2,
						title: '已过期',
						// cnt: 0,
						// loadingType: 'more',
						// datas: [],
						// couponDatas: [],
					}
				],
				
				
				reqdata: {
					page: 1,
					rows: 10
				},
				scrollLeft: 0
			};
		},
		watch: {
			tabCurrentIndex(nv, ov) {
				this.loadData('tab_change', 1);
			}
		},
		onLoad(options) {
			this.loadData();
		},
		// 下拉刷新
		onPullDownRefresh() {
			// this.loadData('refresh');
		},
		// 上拉加载更多
		onReachBottom() {
			// this.loadData();
		},
		methods: {
			// 加载数据
			loadData(source = 'add', loading) {
				// 获取当前 nav
				
				let cur_nav = this.navList[this.tabCurrentIndex];
				this.couponStatus = cur_nav.id;
				this.reqdata.state = cur_nav.state;
				
				// this.couponStatus = 0;
				
				// this.getUserCouponsFunc();
				if( this.oneloading === true ){
					this.oneloading = false,
					this.getUserCouponsFunc();
				};
				
				
				
				console.log("<==================loadData")
				// if (cur_nav.loadingType === 'loading') {
				// 	//防止重复加载
				// 	return;
				// }

				
				// if (loading == 1 || source == 'refresh') {
				// 	this.reqdata.page = 1;
				// }
				
				// if (source.type) {
				// 	source.type = source.type.toLowerCase();
				// }
				
				// if (source === 'add' || source.type == 'scrolltolower') {
				// 	if (cur_nav.loadingType == 'nomore') {
				// 		return;
				// 	}
				// 	cur_nav.loadingType = 'loading';
				// } else {
				// 	cur_nav.loadingType = 'more';
				// }
				
				
				
				
				
				// this.$func.usemall.call('member/coupon', this.reqdata).then(res => {

				// 	cur_nav.loaded = true;

				// 	if (res.code === 200) {
				// 		if (loading == 1 || source == 'refresh') {
				// 			cur_nav.datas = [];
				// 		}

				// 		if (this.reqdata.page == 1) {
				// 			let _nav = {};
				// 			for (let _state in res.datas.dynamic) {
				// 				_nav = this.navList.find(x => x.state == _state);
				// 				if (_nav && _nav.state) {
				// 					_nav.cnt = res.datas.dynamic[_state];
				// 				}
				// 			}
				// 		}

				// 		if (res.datas.length > 0) {
				// 			let __datas = [];
				// 			res.datas.forEach(row => {
				// 				row.end_time = row.end_time.substring(0, 10).replace(/-/g, '.');
				// 				__datas.push(row);
				// 			});

				// 			cur_nav.datas = [...cur_nav.datas, ...__datas];

				// 			if (res.datas.length >= this.reqdata.rows) {
				// 				if (this.reqdata.page == 1) {
				// 					cur_nav.hasmore = true;
				// 				}
				// 				this.reqdata.page++;
				// 				cur_nav.loadingType = 'more';
				// 			} else {
				// 				cur_nav.loadingType = 'nomore';
				// 			}
				// 		} else {
				// 			cur_nav.loadingType = 'nomore';
				// 		}
				// 	}

				// 	if (loading == 1) {
				// 		uni.hideLoading();
				// 	} else if (source == 'refresh') {
				// 		uni.stopPullDownRefresh();
				// 	}

				// 	this.navData = cur_nav;
				// 	console.log(JSON.stringify(this.navData), "<=========coupon_navData");
				// });


			},


			
			// swiper 切换
			changeTab(e) {
				this.tabCurrentIndex = e.target.current;
				// this.couponDatas = [];
				// this.getUserCouponsFunc();
				console.log("<==================changeTab")
			},
			// 顶部tab点击
			tabClick(index) {
				// this.couponDatas = [];
				this.tabCurrentIndex = index;
				this.couponStatus = index;
				console.log(this.couponStatus,"<=================index.this.couponStatus")
				this.getUserCouponsFunc();
				console.log("<==================tabClick")
				
			},
			// 去使用
			use(options) {
				
				// console.log(options,"<=================useruser1")
				// console.log(this.couponStatus,"<=================useruser2")
				if (this.couponStatus == 0){
					this.$api.togoodslist({});
				}else{
					return;
				}
				// console.log(this.couponStatus,"<=================useruser3")
					
					
					
			},
			
			//查询用户优惠券
			async getUserCouponsFunc(){
				this.couponDatas = [];
				
				const response = await queryUserCouponsApi({
					uid: this?.member?.id ?? "",
					state: this?.couponStatus ?? 0,
				}).catch(() => {});
				if (response?.code === 200) {
				// 	const _data = [...this.orderList, ...(response?.data?.records ?? [])];
				this.couponDatas = [...this.couponDatas, ...(response?.data?.records ?? [])];
				// this.couponDatas =	this.couponDatas.map(item =>({
				// 	let item.state = item.users.users_coupons.state
				// }))
				
				// this.couponDatas = this.couponDatas.map(item => {
				//   // 创建一个新的对象，包含原来的属性和新添加的 state 字段
				//   return {
				//     ...item, // 将原来的属性拷贝到新对象中
				//     state: item?.users[0]?.users_coupons?.state // 添加新的 state 字段
				//   };
				// });

				console.log(this.couponDatas, "<=====couponDatas===========getUserCouponsFunc111");
				
				this.new_time = new Date().getTime();
				
				
				
				this.couponDatas = this.couponDatas.map(item => {
					// if(item.users_coupons.state === 0 ){
						let dateString  = item.end_time;
						let dateObj = new Date(dateString).getTime();
						if(this.new_time > dateObj){
							// 如果优惠券已过期，则改为过期状态
							if(item.users_coupons.state == 0){
								this.new_status = 2;
								this.updateUserCouponsFunc(item);
							}
						}
						// 如果优惠券未过期，则改为未过期状态
						else if(this.new_time < dateObj){
							if(item.users_coupons.state == 2){
								this.new_status = 0;
								this.updateUserCouponsFunc(item);
							}
						}
						
					// }
					return item;
				  // 创建一个新的对象，包含原来的属性和新添加的 state 字段
				  // return {
				  //   ...item, // 将原来的属性拷贝到新对象中
				  //   state: item?.users[0]?.users_coupons?.state // 添加新的 state 字段
				  // };
				});
				
				
				console.log(this.couponDatas, "<=====couponDatas===========getUserCouponsFunc222");

				} else {
					this.$api.msg(response?.msg ?? '服务器繁忙，请稍后再试');
				}
			},
			
			//修改优惠券状态
			async updateUserCouponsFunc(item){
				const response = await updateUserCouponsApi({
					id: item?.users_coupons?.id ?? "",
					state: this?.new_status,
				}).catch(() => {})
				if(response.code == 200){
					
				}else{
					this.$api.msg(response?.msg ?? "服务器繁忙，请稍后再试");
				}
			},
			
			
		}
	};
</script>

<style lang="scss">
	page,
	.container {
		min-height: 100%;
		background: $page-color-base;
	}

	.container {
		padding-top: 7vh;
	}

	/* 优惠券状态区 */
	.navbar-area {
		top: 0;
		white-space: nowrap;

		.state-area {
			height: 7vh;
			box-shadow: 0 1px 5px rgba(0, 0, 0, 0.06);
			z-index: 10;
		}

		.nav-item {
			flex: 1;

			&.active {
				&:after {
					content: '';
					position: absolute;
					left: 50%;
					transform: translate(-50%);
					bottom: 0;
					width: 44px;
					height: 0;
					border-bottom: 2px solid $base-color;
				}
			}
		}
	}

	/* #ifdef H5 */
	.navbar-area {
		margin-top: calc(44px + env(safe-area-inset-top));
	}

	/* #endif */

	/* 优惠券轮播区 */
	.swiper-area {
		height: 93vh;
	}

	.coupon_box {
		position: relative;

		&:last-child {
			margin-bottom: 20rpx;
		}

		.left {
			background-color: $base-color;
			color: #fff;
			width: 30%;

			.price {
				color: #fff !important;
			}
		}

		.right {
			margin-left: 30%;
		}

		.discount {
			font-weight: 580;
		}

		.discount::after {
			content: '折';
			font-size: 24rpx;
			margin-left: 6rpx;
		}

		.border-line {
			border-bottom: 1px dotted #ededed;
		}
	}

	.disabled {
		.left {
			background-color: #d9d9d9;
			color: #b2b2b2 !important;

			.price {
				color: #b2b2b2 !important;
			}
		}

		.iconfont {
			position: absolute;
			top: 0rpx;
			right: 30rpx;
			font-size: 110rpx;
		}
	}
</style>